package tv.youxing.android.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lzy.okgo.db.DownloadManager;
import com.lzy.okgo.model.Progress;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;

import java.io.File;
import java.text.NumberFormat;
import java.util.List;
import java.util.Map;

import tv.youxing.android.R;
import tv.youxing.android.entity.DownloadInfoModel;
import tv.youxing.android.ui.LocalVideoPlayActivity;
import tv.youxing.android.ui.test.test3DownloadListener;
import tv.youxing.android.utils.PicassoUtils;
import tv.youxing.android.utils.UtilTools;

/**
 * Created by Administrator on 2017/7/2.
 * 所有的下载列表界面管理器
 */

public class Download_AllManager_Adapter extends BaseAdapter {

    private Context context;
    private LayoutInflater layoutInflater;


    public static final int TYPE_ALL = 0;
    public static final int TYPE_FINISH = 1;
    public static final int TYPE_ING = 2;

    private List<DownloadTask> values;
    private NumberFormat numberFormat;
    private int type;


    public Download_AllManager_Adapter(Context context) {
        this.context = context;
        numberFormat = NumberFormat.getPercentInstance();
        numberFormat.setMinimumFractionDigits(2);
        layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
    }

    public void updateData(int type) {
        //这里是将数据库的数据恢复
        this.type = type;
        if (type == TYPE_ALL) values = OkDownload.restore(DownloadManager.getInstance().getAll());
        if (type == TYPE_FINISH) values = OkDownload.restore(DownloadManager.getInstance().getFinished());
        if (type == TYPE_ING) values = OkDownload.restore(DownloadManager.getInstance().getDownloading());

        for (DownloadTask value : values) {
            value.register(null);
        }

        notifyDataSetChanged();
    }

    public void unRegister() {
        Map<String, DownloadTask> taskMap = OkDownload.getInstance().getTaskMap();
        for (DownloadTask task : taskMap.values()) {
            task.unRegister("ListDownloadListener_" + type);
        }
    }

    @Override
    public int getCount() {
        return values==null?0:values.size();
    }

    @Override
    public Object getItem(int position) {
        return values.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if (viewHolder==null) {
            viewHolder = new ViewHolder();
            convertView = layoutInflater.inflate(R.layout.download_item_manager, null);


            //新版
            viewHolder.ll_root = convertView.findViewById(R.id.root);
            viewHolder.head = convertView.findViewById(R.id.ivIcon);
            viewHolder.title = convertView.findViewById(R.id.title);
            viewHolder.player_count = convertView.findViewById(R.id.play_count);
            viewHolder.common_count = convertView.findViewById(R.id.comment_count);


            //旧版
            viewHolder.icon = convertView.findViewById(R.id.icon);
            viewHolder.name = convertView.findViewById(R.id.name);
            viewHolder.priority = convertView.findViewById(R.id.priority);
            viewHolder.downloadSize = convertView.findViewById(R.id.downloadSize);
            viewHolder.tvProgress = convertView.findViewById(R.id.tvProgress);
            viewHolder.netSpeed = convertView.findViewById(R.id.netSpeed);
            viewHolder.pbProgress = convertView.findViewById(R.id.pbProgress);
            viewHolder.download = convertView.findViewById(R.id.start);
            viewHolder.remove = convertView.findViewById(R.id.remove);
            viewHolder.restart = convertView.findViewById(R.id.restart);

            convertView.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder) convertView.getTag();
        }


        DownloadTask task = values.get(position);
        String holderTag = type + "_" + task.progress.tag;
        task.register(new ListDownloadListener(holderTag, viewHolder))//
                .register(new test3DownloadListener() {
                });

        viewHolder.setTag(holderTag);
        viewHolder.setTask(task);
        viewHolder.bind();
        viewHolder.refresh(task.progress);


        return convertView;
    }


    class ViewHolder{


        //        新版的空间
        private LinearLayout ll_root;
        private ImageView head;
        private TextView title;
        private TextView player_count;
        private TextView common_count;


        //        旧版的控件
        ImageView icon;
        TextView name;
        TextView priority;
        TextView downloadSize;
        TextView tvProgress;
        TextView netSpeed;
        ProgressBar pbProgress;
        Button download;
        Button remove;
        Button restart;


        private DownloadTask task;

        String tag;

        public void setTask(DownloadTask task) {
            this.task = task;
        }

        public void bind() {
            Progress progress = task.progress;
            DownloadInfoModel apk = (DownloadInfoModel) progress.extra1;


            switch (progress.status) {
                case Progress.PAUSE:
                case Progress.NONE:
                case Progress.ERROR:
                    break;
                case Progress.LOADING:
                    break;
                case Progress.FINISH:

                    System.out.println("文件路径是:" + progress.filePath);

                    priority.setVisibility(View.GONE);
//                        downloadSize.setVisibility(View.GONE);
                    netSpeed.setVisibility(View.GONE);
                    priority.setVisibility(View.GONE);
                    pbProgress.setVisibility(View.GONE);
                    break;
            }

            if (apk != null) {
                PicassoUtils.loadImageView(context,apk.iconUrl,icon);
                name.setText(apk.name);
                priority.setText(String.format("优先级：%s", progress.priority));
            } else {
                name.setText(progress.fileName);
            }
            download.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    start();
                }
            });
            remove.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    remove();
                }
            });
            restart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    restart();
                }
            });


            //新版
            if (apk != null) {
                PicassoUtils.loadImageView(context,apk.iconUrl,head);
                title.setText(apk.name);
                player_count.setText(apk.playerCount + "次播放");
                common_count.setText(apk.commonCount + "评论");
            } else {
                title.setText(progress.fileName);
            }
            ll_root.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    start();
                    dialog2();
                }
            });


        }

        //适配操作的dialog
        private void dialog2() {
            final String items[]={"开始","删除","重新下载"};
            //dialog参数设置
            AlertDialog.Builder builder=new AlertDialog.Builder(context);  //先得到构造器
//            builder.setTitle("提示"); //设置标题
            //builder.setMessage("是否确认退出?"); //设置内容
            builder.setIcon(R.mipmap.ic_launcher);//设置图标，图片id即可
            //设置列表显示，注意设置了列表显示就不要设置builder.setMessage()了，否则列表不起作用。
            builder.setItems(items,new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    if (items[which].equals("开始")) {
                        start();
                    } else if (items[which].equals("删除")) {
                        remove();
                    } else if (items[which].equals("重新下载")) {
                        restart();
                    }

                }
            });
            builder.setPositiveButton("关闭",new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();
        }


        public void start() {
            Progress progress = task.progress;
            switch (progress.status) {
                case Progress.PAUSE:
                case Progress.NONE:
                case Progress.ERROR:
                    task.start();
                    break;
                case Progress.LOADING:
                    task.pause();
                    break;
                case Progress.FINISH:
                    if (UtilTools.fileIsExists(task.progress.filePath)) {
                        System.out.println("文件存在");
                        Intent intent  = new Intent(context, LocalVideoPlayActivity.class);
                        intent.putExtra("filename",task.progress.filePath);
                        context.startActivity(intent);
                    } else {
                        System.out.println("文件不存在");
                    }

//                    if (ApkUtils.isAvailable(context, new File(progress.filePath))) {
//                        ApkUtils.uninstall(context, ApkUtils.getPackageName(context, progress.filePath));
//                    } else {
//                        ApkUtils.install(context, new File(progress.filePath));
//                    }
                    break;
            }
            refresh(progress);
        }

        public void remove() {
            task.remove(true);
            updateData(type);
        }

        public void restart() {
            task.restart();
        }


        public void refresh(Progress progress) {
            String currentSize = Formatter.formatFileSize(context, progress.currentSize);
            String totalSize = Formatter.formatFileSize(context, progress.totalSize);
            downloadSize.setText(currentSize + "/" + totalSize);
            priority.setText(String.format("优先级：%s", progress.priority));
            switch (progress.status) {
                case Progress.NONE:
                    netSpeed.setText("停止");
                    download.setText("下载");
                    break;
                case Progress.PAUSE:
                    netSpeed.setText("暂停中");
                    download.setText("继续");
                    break;
                case Progress.ERROR:
                    netSpeed.setText("下载出错");
                    download.setText("出错");
                    break;
                case Progress.WAITING:
                    netSpeed.setText("等待中");
                    download.setText("等待");
                    break;
                case Progress.FINISH:
//                    if (ApkUtils.isAvailable(context, new File(progress.filePath))) {
//                        download.setText("卸载");
//                    } else {
//                        download.setText("安装");
//                    }
                    download.setText("完成");
                    netSpeed.setText("下载完成");
                    break;
                case Progress.LOADING:
                    String speed = Formatter.formatFileSize(context, progress.speed);
                    netSpeed.setText(String.format("%s/s", speed));
                    download.setText("暂停");
                    break;
            }
            tvProgress.setText(numberFormat.format(progress.fraction));
            pbProgress.setMax(10000);
            pbProgress.setProgress((int) (progress.fraction * 10000));
        }


        public void setTag(String tag) {
            this.tag = tag;
        }

        public String getTag() {
            return tag;
        }
    }


    private class ListDownloadListener extends DownloadListener {

        private ViewHolder holder;

        ListDownloadListener(Object tag, ViewHolder holder) {
            super(tag);
            this.holder = holder;
        }

        @Override
        public void onStart(Progress progress) {
        }

        @Override
        public void onProgress(Progress progress) {
            if (tag == holder.getTag()) {
                holder.refresh(progress);
            }
        }

        @Override
        public void onError(Progress progress) {
            Throwable throwable = progress.exception;
            if (throwable != null) throwable.printStackTrace();
        }

        @Override
        public void onFinish(File file, Progress progress) {
//            Toast.makeText(context, "下载完成:" + progress.filePath, Toast.LENGTH_SHORT).show();
            updateData(type);
        }

        @Override
        public void onRemove(Progress progress) {
        }
    }
}
